// module.exports = function (source, map) {
//   this.callback(
//     null,
//     "module.exports = function(Component) {Component.options.__docs = " +
//       JSON.stringify(source) +
//       "}",
//     map
//   );
// };

const fs = require("fs");
const { baseParse } = require("@vue/compiler-core");

module.exports = function (source, map) {
  // 1. 获取带有 <docs /> 标签的文件完整路径
  const { resourcePath } = this;
  // 2. 读取文件内容
  const file = fs.readFileSync(resourcePath).toString();

  // 3. 通过 baseParse 将字符串模板转换成 AST 抽象语法树
  // 3.1 获取源代码信息标签内容
  const sourceInfoTag = baseParse(file).children.find(n => {
    return n.tag === "docs";
  });

  if (!sourceInfoTag) {
    return;
  }

  // 3.2 标题
  const sourceTitleTag = sourceInfoTag.children.find(
    n => n.tag === "docs-title"
  );
  // 3.3 描述
  const sourceDescTag = sourceInfoTag.children.find(n => n.tag === "docs-desc");

  const title = (sourceTitleTag && sourceTitleTag.children[0] || {}).content;

  const desc = (sourceDescTag && sourceDescTag?.children[0] || {}).content;

  // 4. 将 <source-info></source-info> 标签和内容抽离
  const main = file.split(sourceInfoTag.loc.source).join("").trim();

  // 5. 回到并添加到 组件对象上面
  this.callback(
    null,
    `export default function (Component) {
          Component.options.__sourceCode = ${JSON.stringify(main)}
          Component.options.__docs = ${JSON.stringify(source)}
          Component.options.__title = ${JSON.stringify(title)}
          Component.options.__desc = ${JSON.stringify(desc)}
        }`,
    map
  );
};
